package library.view;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import library.controller.LibraryControllerListener;
import library.dao.Impl.BookDaoImpl;
import library.dao.Impl.BorrowHistoryDao;
import library.dao.Impl.UserDaoImpl;
import library.pojo.Book;
import library.pojo.BorrowHistory;
import library.service.LibraryService;

public class BorrowHistoryPanel extends JPanel {
	private JTextField historySearchTextField;
	private BorrowHistoryDao bhDao = null;
	private JTable table;
	private List<BorrowHistory> borrowHistoryList = null;
	private JComboBox searchTypeComboBox;
	private JScrollPane tablePanel;
	private String bn;
	private int remainTime;
	private LibraryService libraryService;
	public JScrollPane scrollPane;
	private int selRow = -1;
	private UserDaoImpl userDao = new UserDaoImpl();
	private java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	private ImageIcon icon;
	private Image img;

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this);
	}

	public BorrowHistoryPanel(List<Book> bookList, LibraryControllerListener libraryControllerListener)
			throws ParseException {
		setBounds(100, 100, 1200, 750);
		this.setLayout(null);

		icon = new ImageIcon("res/2.png");
		img = icon.getImage();
		
		JLabel message = new JLabel("请选择查询类型:");
		message.setFont(new Font("宋体", Font.PLAIN, 18));
		message.setBounds(189, 32, 248, 18);
		this.add(message);

		String[] ways = { "按照isbn查询", "按照书名查询", "按照借阅者查询", "按照图书状态查询" };
		searchTypeComboBox = new JComboBox(ways);
		searchTypeComboBox.setFont(new Font("宋体", Font.PLAIN, 14));
		searchTypeComboBox.setToolTipText("");
		searchTypeComboBox.setBounds(189, 63, 248, 24);
		this.add(searchTypeComboBox);

		historySearchTextField = new JTextField();
		historySearchTextField.setBounds(514, 63, 295, 24);
		this.add(historySearchTextField);
		historySearchTextField.setColumns(10);

		JButton searchButton = new JButton("查询");
		searchButton.setIcon(new ImageIcon("res/search.png"));
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					bookSearchActionPerformed(e);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		searchButton.setActionCommand("searchPost");
		searchButton.setFont(new Font("宋体", Font.PLAIN, 18));
		searchButton.setBounds(830, 62, 99, 27);
		this.add(searchButton);

		JButton returnButton = new JButton("还书");
		returnButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					bookReturnActionPerformed(e);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		returnButton.setFont(new Font("宋体", Font.PLAIN, 18));
		returnButton.setBounds(320, 617, 89, 27);
		this.add(returnButton);

		JButton renewButton = new JButton("续借");
		renewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					bookRenewActionPerformed(e);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		renewButton.setFont(new Font("宋体", Font.PLAIN, 18));
		renewButton.setBounds(510, 617, 89, 27);
		this.add(renewButton);

		JButton resetButton = new JButton("刷新");
		resetButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					bookResetActionPerformed(e);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		resetButton.setFont(new Font("宋体", Font.PLAIN, 18));
		resetButton.setBounds(700, 617, 89, 27);
		this.add(resetButton);

		scrollPane = new JScrollPane();
		scrollPane = this.getContactJPanel();
		scrollPane.setBounds(189, 120, 740, 478);
		this.add(scrollPane);

	}

	/**
	 * 续借事件处理
	 * 
	 * @throws ParseException
	 */
	protected void bookRenewActionPerformed(ActionEvent e) throws ParseException {
		BookDaoImpl bookDao = new BookDaoImpl();
		if (selRow < 0) {
			JOptionPane.showMessageDialog(null, "请选择一本书！");
			return;
		}
		if (bookDao.findBookState(bn).equals("在馆")) {
			JOptionPane.showMessageDialog(null, "该书已归还！");
			return;
		}
		if (bookDao.findBookState(bn).equals("借出")) {
			bhDao = new BorrowHistoryDao();
			bhDao.updateRenewState(bn);
			bhDao.updateCount3(bn);
			bhDao.updateCount2(bn);
			bhDao.updateCount1(bn);
			List<BorrowHistory> borrowHistoryList = new ArrayList<BorrowHistory>();
			borrowHistoryList = LibraryService.findAllBookBorrowHistory();
			Iterator<BorrowHistory> iters = borrowHistoryList.iterator();
			int j = 0;
			while (iters.hasNext()) {
				BorrowHistory borrowhistory = iters.next();
				if (borrowhistory.getCount() == 3) {
					j = -1;
				}
			}
			if (j == 0) {
				remainTime = remainTime + 30;
				System.out.println(remainTime);
				bhDao.updateRemainTime(bn, remainTime, "续借");
				JOptionPane.showMessageDialog(null, "续借成功！");
			} else if (j == -1) {
				JOptionPane.showMessageDialog(null, "续借次数已达上限，续借失败！");
			}
		}

		selRow = -1;
		borrowHistoryList = new ArrayList<BorrowHistory>();
		borrowHistoryList = LibraryService.findAllBookBorrowHistory();
		String name[] = { "isbn", "书名", "借阅人", "借阅日期", "借阅剩余天数", "图书状态" };
		Object data[][] = new Object[borrowHistoryList.size()][6];
		Iterator<BorrowHistory> iter = borrowHistoryList.iterator();
		int i = 0;
		while (iter.hasNext()) {
			BorrowHistoryDao Dao = new BorrowHistoryDao();
			BorrowHistory borrowhistory = iter.next();
			Date date1 = formatter.parse(borrowhistory.getBorrowDate());
			Date date2 = new Date();
			int time = differentDaysByMillisecond(date1, date2);
			int rTime = 0;
			if (borrowhistory.getBorrowState().equals("借出")) {
				rTime = time;
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "借出");
			} else if (borrowhistory.getBorrowState().equals("归还")) {
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "归还");
			}

			data[i][0] = borrowhistory.getIsbn();
			data[i][1] = borrowhistory.getBookName();
			data[i][2] = userDao.register(borrowhistory.getBorrowUser()).getName();
			data[i][3] = borrowhistory.getBorrowDate();
			data[i][4] = borrowhistory.getRemainTime();
			data[i][5] = borrowhistory.getBorrowState();
			i++;
		}
		DefaultTableModel tableModel = new DefaultTableModel(data, name);
		table = new JTable(tableModel);
		table.getTableHeader().setFont(new Font("宋体", Font.BOLD, 16)); // 表头字体
		table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 表体字体
		table.getTableHeader().setPreferredSize(new Dimension(1, 30)); // 表头高度
		table.setRowHeight(table.getRowHeight() + 15); // 表体高度
		table.repaint();
		tablePanel = new JScrollPane(table);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent e) {
				selRow = table.getSelectedRow(); // 得到选中的行
				if (selRow >= 0) {
					bn = borrowHistoryList.get(selRow).getIsbn();
					remainTime = borrowHistoryList.get(selRow).getRemainTime();
				}
				System.out.println(selRow);
				System.out.println(bn);
			}
		});
		this.remove(scrollPane);
		scrollPane = getContactJPanel();
		scrollPane.setBounds(189, 120, 740, 478);
		this.add(scrollPane);
		this.validate();
	}

	/**
	 * 还书事件处理
	 * 
	 * @throws ParseException
	 */
	protected void bookReturnActionPerformed(ActionEvent e) throws ParseException {
		BookDaoImpl bookDao = new BookDaoImpl();
		if (selRow < 0) {
			JOptionPane.showMessageDialog(null, "请选择一本书！");
			return;
		}
		if (bookDao.findBookState(bn).equals("在馆")) {
			JOptionPane.showMessageDialog(null, "该书已归还！");
			return;
		}
		if (bookDao.findBookState(bn).equals("借出")) {
			bhDao = new BorrowHistoryDao();
			bhDao.updateState(bn);
			bhDao.updateCount0(bn);
			bookDao.updateStateBorrow(bn, "在馆");
		}
		JOptionPane.showMessageDialog(null, "还书成功！");

		selRow = -1;
		borrowHistoryList = new ArrayList<BorrowHistory>();
		borrowHistoryList = LibraryService.findAllBookBorrowHistory();
		String name[] = { "isbn", "书名", "借阅人", "借阅日期", "借阅剩余天数", "图书状态" };
		Object data[][] = new Object[borrowHistoryList.size()][6];
		Iterator<BorrowHistory> iter = borrowHistoryList.iterator();
		int i = 0;
		while (iter.hasNext()) {
			BorrowHistoryDao Dao = new BorrowHistoryDao();
			BorrowHistory borrowhistory = iter.next();
			Date date1 = formatter.parse(borrowhistory.getBorrowDate());
			Date date2 = new Date();
			int time = differentDaysByMillisecond(date1, date2);
			int rTime = 0;
			if (borrowhistory.getBorrowState().equals("借出")) {
				rTime = time;
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "借出");
			} else if (borrowhistory.getBorrowState().equals("归还")) {
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "归还");
			}

			data[i][0] = borrowhistory.getIsbn();
			data[i][1] = borrowhistory.getBookName();
			data[i][2] = userDao.register(borrowhistory.getBorrowUser()).getName();
			data[i][3] = borrowhistory.getBorrowDate();
			data[i][4] = borrowhistory.getRemainTime();
			data[i][5] = borrowhistory.getBorrowState();
			i++;
		}
		DefaultTableModel tableModel = new DefaultTableModel(data, name);
		table = new JTable(tableModel);
		table.getTableHeader().setFont(new Font("宋体", Font.BOLD, 16)); // 表头字体
		table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 表体字体
		table.getTableHeader().setPreferredSize(new Dimension(1, 30)); // 表头高度
		table.setRowHeight(table.getRowHeight() + 15); // 表体高度
		table.repaint();
		tablePanel = new JScrollPane(table);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent e) {
				selRow = table.getSelectedRow(); // 得到选中的行
				if (selRow >= 0) {
					bn = borrowHistoryList.get(selRow).getIsbn();
					remainTime = borrowHistoryList.get(selRow).getRemainTime();
				}
				System.out.println(selRow);
				System.out.println(bn);
			}
		});
		this.remove(scrollPane);
		scrollPane = getContactJPanel();
		scrollPane.setBounds(189, 120, 740, 478);
		this.add(scrollPane);
		this.validate();
	}

	/**
	 * 刷新事件处理
	 * 
	 * @throws ParseException
	 */
	public void bookResetActionPerformed(ActionEvent e) throws ParseException {
		selRow = -1;
		borrowHistoryList = new ArrayList<BorrowHistory>();
		borrowHistoryList = LibraryService.findAllBookBorrowHistory();
		String name[] = { "isbn", "书名", "借阅人", "借阅日期", "借阅剩余天数", "图书状态" };
		Object data[][] = new Object[borrowHistoryList.size()][6];
		Iterator<BorrowHistory> iter = borrowHistoryList.iterator();
		int i = 0;
		while (iter.hasNext()) {
			BorrowHistoryDao Dao = new BorrowHistoryDao();
			BorrowHistory borrowhistory = iter.next();
			Date date1 = formatter.parse(borrowhistory.getBorrowDate());
			Date date2 = new Date();
			int time = differentDaysByMillisecond(date1, date2);
			int rTime = 0;
			if (borrowhistory.getBorrowState().equals("借出")) {
				rTime = time;
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "借出");
			} else if (borrowhistory.getBorrowState().equals("归还")) {
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "归还");
			}

			data[i][0] = borrowhistory.getIsbn();
			data[i][1] = borrowhistory.getBookName();
			data[i][2] = userDao.register(borrowhistory.getBorrowUser()).getName();
			data[i][3] = borrowhistory.getBorrowDate();
			data[i][4] = borrowhistory.getRemainTime();
			data[i][5] = borrowhistory.getBorrowState();
			i++;
		}
		DefaultTableModel tableModel = new DefaultTableModel(data, name);
		table = new JTable(tableModel);
		table.getTableHeader().setFont(new Font("宋体", Font.BOLD, 16)); // 表头字体
		table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 表体字体
		table.getTableHeader().setPreferredSize(new Dimension(1, 30)); // 表头高度
		table.setRowHeight(table.getRowHeight() + 15); // 表体高度
		table.repaint();
		tablePanel = new JScrollPane(table);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent e) {
				selRow = table.getSelectedRow(); // 得到选中的行
				if (selRow >= 0) {
					bn = borrowHistoryList.get(selRow).getIsbn();
					remainTime = borrowHistoryList.get(selRow).getRemainTime();
				}
				System.out.println(selRow);
				System.out.println(bn);
			}
		});
		this.remove(scrollPane);
		scrollPane = getContactJPanel();
		scrollPane.setBounds(189, 120, 740, 478);
		this.add(scrollPane);
		this.validate();
		JOptionPane.showMessageDialog(null, "刷新成功！");
	}

	/**
	 * 获得总表格
	 * 
	 * @throws ParseException
	 */
	public JScrollPane getContactJPanel() throws ParseException {
		selRow = -1;
		borrowHistoryList = new ArrayList<BorrowHistory>();
		borrowHistoryList = LibraryService.findAllBookBorrowHistory();
		String name[] = { "isbn", "书名", "借阅人", "借阅日期", "借阅剩余天数", "图书状态" };
		Object data[][] = new Object[borrowHistoryList.size()][6];
		Iterator<BorrowHistory> iter = borrowHistoryList.iterator();
		int i = 0;
		while (iter.hasNext()) {
			BorrowHistoryDao Dao = new BorrowHistoryDao();
			BorrowHistory borrowhistory = iter.next();
			Date date1 = formatter.parse(borrowhistory.getBorrowDate());
			Date date2 = new Date();
			int time = differentDaysByMillisecond(date1, date2);
			int rTime = 0;
			if (borrowhistory.getBorrowState().equals("借出")) {
				rTime = time;
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "借出");
			} else if (borrowhistory.getBorrowState().equals("归还")) {
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "归还");
			}

			data[i][0] = borrowhistory.getIsbn();
			data[i][1] = borrowhistory.getBookName();
			data[i][2] = userDao.register(borrowhistory.getBorrowUser()).getName();
			data[i][3] = borrowhistory.getBorrowDate();
			data[i][4] = borrowhistory.getRemainTime();
			data[i][5] = borrowhistory.getBorrowState();
			i++;
		}
		DefaultTableModel tableModel = new DefaultTableModel(data, name);
		table = new JTable(tableModel);
		table.getTableHeader().setFont(new Font("宋体", Font.BOLD, 16)); // 表头字体
		table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 表体字体
		table.getTableHeader().setPreferredSize(new Dimension(1, 30)); // 表头高度
		table.setRowHeight(table.getRowHeight() + 15); // 表体高度
		table.repaint();
		tablePanel = new JScrollPane(table);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent e) {
				selRow = table.getSelectedRow(); // 得到选中的行
				if (selRow >= 0) {
					bn = borrowHistoryList.get(selRow).getIsbn();
					remainTime = borrowHistoryList.get(selRow).getRemainTime();
				}
				System.out.println(selRow);
				System.out.println(bn);
			}
		});

		return tablePanel;
	}

	/**
	 * 查询事件处理
	 * 
	 * @throws ParseException
	 */
	public void bookSearchActionPerformed(ActionEvent evt) throws ParseException {
		selRow = -1;
		borrowHistoryList = null;
		if (searchTypeComboBox.getSelectedItem().equals("按照isbn查询")) {
			String isbnInput = historySearchTextField.getText().trim();
			libraryService = new LibraryService();
			borrowHistoryList = libraryService.getIsbn(isbnInput);
		}
		if (searchTypeComboBox.getSelectedItem().equals("按照书名查询")) {
			String bookNameInput = historySearchTextField.getText().trim();
			libraryService = new LibraryService();
			borrowHistoryList = libraryService.getbookName(bookNameInput);
		}
		if (searchTypeComboBox.getSelectedItem().equals("按照借阅者查询")) {
			String borrowUserInput = historySearchTextField.getText().trim();
			libraryService = new LibraryService();
			borrowHistoryList = libraryService.getBorrowUser(borrowUserInput);
		}
		if (searchTypeComboBox.getSelectedItem().equals("按照图书状态查询")) {
			String stateInput = historySearchTextField.getText().trim();
			libraryService = new LibraryService();
			borrowHistoryList = libraryService.getState(stateInput);
		}

		String name[] = { "isbn", "书名", "借阅人", "借阅日期", "借阅剩余天数", "图书状态" };
		Object data[][] = new Object[borrowHistoryList.size()][6];
		Iterator<BorrowHistory> iter = borrowHistoryList.iterator();
		int i = 0;
		while (iter.hasNext()) {
			BorrowHistoryDao Dao = new BorrowHistoryDao();
			BorrowHistory borrowhistory = iter.next();
			Date date1 = formatter.parse(borrowhistory.getBorrowDate());
			Date date2 = new Date();
			int time = differentDaysByMillisecond(date1, date2);
			int rTime = 0;
			if (borrowhistory.getBorrowState().equals("借出")) {
				rTime = time;
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "借出");
			} else if (borrowhistory.getBorrowState().equals("归还")) {
				Dao.updateRemainTime(borrowhistory.getIsbn(), rTime, "归还");
			}

			data[i][0] = borrowhistory.getIsbn();
			data[i][1] = borrowhistory.getBookName();
			data[i][2] = userDao.register(borrowhistory.getBorrowUser()).getName();
			data[i][3] = borrowhistory.getBorrowDate();
			data[i][4] = borrowhistory.getRemainTime();
			data[i][5] = borrowhistory.getBorrowState();
			i++;
		}
		DefaultTableModel tableModel = new DefaultTableModel(data, name);
		table = new JTable(tableModel);
		table.getTableHeader().setFont(new Font("宋体", Font.BOLD, 16)); // 表头字体
		table.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 表体字体
		table.getTableHeader().setPreferredSize(new Dimension(1, 30)); // 表头高度
		table.setRowHeight(table.getRowHeight() + 15); // 表体高度
		table.repaint();
		tablePanel = new JScrollPane(table);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent e) {
				selRow = table.getSelectedRow(); // 得到选中的行
				if (selRow >= 0) {
					bn = borrowHistoryList.get(selRow).getIsbn();
					remainTime = borrowHistoryList.get(selRow).getRemainTime();
				}
				System.out.println(selRow);
				System.out.println(bn);
			}
		});
		this.remove(scrollPane);
		scrollPane = tablePanel;
		scrollPane.setBounds(189, 120, 740, 478);
		this.add(scrollPane);
		this.validate();
	}

	public static int differentDaysByMillisecond(Date date1, Date date2) {
		int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
		int remaindays = 90 - days;
		return remaindays;
	}
}
